<template>
  <div class="app-container">
    <!--工具栏-->

    <div class="cardBtnBox">
      <el-button
        :loading="loading"
        type="primary"
        @click="submit"
      >保存</el-button>
    </div>

    <div class="head-container">
      <div class="fieldset">
        <label class="group">基本信息</label>
        <el-form
          ref="form"
          class="formClass"
          :model="form"
          :rules="rules"
          size="small"
          label-width="120px"
        >
          <!-- <el-form-item label="任务ID" class="itemRow" prop="jobId">
            <el-input v-model="form.jobId" class="filedWidth" />
          </el-form-item> -->
          <el-form-item label="项目" class="itemRow">
            <el-input v-model="form.projectId" class="filedWidth" />
          </el-form-item>
          <el-form-item label="任务名称" prop="jobName" class="itemRow">
            <el-input v-model="form.jobName" class="filedWidth" />
          </el-form-item>
          <el-form-item label="执行计划" class="itemRow">
            <el-input v-model="form.cronScript" class="filedWidth" />
          </el-form-item>
          <el-form-item label="备注" class="itemRow2">
            <el-input v-model="form.memo" type="textarea" class="filedWidth" />
          </el-form-item>
        </el-form>
      </div>
      <div v-if="edit" class="fieldset" style="padding-top:55px;">
        <div class="group">
          <el-button
            class="filter-item"
            size="mini"
            type="success"
            icon="el-icon-plus"
            @click="addMigDefMain"
          >添加</el-button>
          <el-button
            class="filter-item"
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="!deleteFlag"
            @click="deleteItem"
          >删除</el-button>
        </div>
        <!--表格渲染-->
        <el-table
          ref="table"
          :data="formData"
          size="small"
          border
          stripe
          style="width: 100%;"
          @row-dblclick="editFiled"
          @selection-change="selectionChangeHandler"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            type="index"
            width="50"
            label="序号"
            align="center"
          />
          <el-table-column prop="code" label="编码" width="200" />
          <el-table-column prop="name" label="名称" width="160" />
          <el-table-column prop="querySql" label="查询SQL">
            <template slot-scope="scope">
              <div class="searchFiled" @dblclick.stop="inputdbl">
                <el-input
                  v-model="scope.row.querySql"
                  type="textarea"
                  rows="4"
                  @change="saveRowData(scope.row)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="execState"
            width="60"
            label="执行中"
            align="center"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.execState == 1">
                <img
                  class="exec-loading"
                  src="../../assets/images/loading.gif"
                >
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80px" align="center">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="执行"
                placement="top-start"
              >
                <el-button
                  size="mini"
                  type="success"
                  icon="el-icon-caret-right"
                  @click="execMigTask(scope.row)"
                />
              </el-tooltip>
            </template>

          </el-table-column>
        </el-table>
      </div>

      <el-dialog
        :visible.sync="migDefMain"
        title="选择迁移定义"
        width="65%"
        top="10vh"
      >
        <div class="dialogHeight">
          <MigDefMainCheck @checkMainItem="checkMainItem" />
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import crudMigJob from '@/api/migJob'
import migJobRelate from '@/api/migJobRelate'
import MigDefMainCheck from '@/views/migrate/migDefMainCheck'
import CRUD, { presenter, header, form, crud } from '@crud/crud'

const defaultForm = {
  jobId: null,
  projectId: null,
  jobName: null,
  cronScript: null,
  memo: null,
  createTime: null,
  updateTime: null
}
export default {
  name: 'MigJobEdit',
  components: {
    MigDefMainCheck
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      idfield: 'jobId',
      title: '迁移任务',
      url: 'api/migJob',
      sort: 'job_id,desc',
      crudMethod: { ...crudMigJob }
    })
  },
  data() {
    return {
      formData: [
        {
          jobId: '',
          migId: '',
          code: '',
          jobName: '',
          querySql: '',
          execState: ''
        }
      ],
      deleteFlag: false,
      selectionArr: [],
      migDefMain: false,
      loading: false,
      permission: {
        add: ['admin', 'migJob:add'],
        edit: ['admin', 'migJob:edit'],
        del: ['admin', 'migJob:del']
      },
      rules: {
        jobId: [{ required: true, message: '任务ID不能为空', trigger: 'blur' }],
        jobName: [
          { required: true, message: '任务名称不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'projectId', display_name: '项目' },
        { key: 'jobName', display_name: '任务名称' }
      ]
    }
  },
  computed: {
    routerParam() {
      return this.$route.query
    }
  },
  watch: {
    routerParam: {
      handler(val) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          target: '.app-container',
          spinner: 'el-icon-loading'
        })
        Object.assign(this.form, this.routerParam)
        this.queryChildList()
        this.edit = true
        // byid请求详情
        const id = this.form.jobId
        if (id) {
          var params = { id }
          crudMigJob.byid(params).then(res => {
            loading.close()
            Object.assign(this.form, res)
          })
        }
      }
    }
  },
  created() {
    const query = this.$route.query
    Object.assign(this.form, query)
    this.edit = query.queryEdit
    // byid请求详情
    const id = this.form.jobId
    if (id) {
      var params = { id }
      crudMigJob.byid(params).then(res => {
        Object.assign(this.form, res)
      })
    }
    this.queryChildList()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return false
    },
    selectionChangeHandler(data, index) {
      this.deleteFlag = data.length > 0
      this.selectionArr = data
    },
    submit() {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.loading = true
        this.edit ? this.customEdit() : this.customAdd()
      })
    },
    /**
     * 执行自定义添加
     */
    customAdd() {
      this.crud.crudMethod.add(this.form).then(res => {
        this.loading = false
        this.edit = true
        this.form.jobId = res.jobId
        this.crud.addSuccessNotify()
      })
    },
    /**
     * 执行自定义编辑
     */
    customEdit() {
      console.log(this.form)
      this.crud.crudMethod.edit(this.form).then(res => {
        this.loading = false
        this.crud.editSuccessNotify()
      })
    },
    queryChildList() {
      const params = {
        jobId: this.form.jobId
      }
      migJobRelate.query(params).then(res => {
        if (res && res.content) {
          const arr = res.content || []
          arr.sort((a, b) => {
            const ac = a.code || ''
            const bc = b.code || ''
            return ac.toLowerCase() < bc.toLowerCase() ? -1 : 1
          })
          this.formData = arr
        }
      })
    },
    deleteItem() {
      var messageStr = `确认删除选中的${this.selectionArr.length}条数据?`
      this.$confirm(messageStr, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const arr = []
          this.selectionArr.map(i => {
            arr.push(i.rtId)
          })
          migJobRelate.del(arr).then(() => {
            this.queryChildList()
          })
        })
        .catch(e => {
          console.error(e.message)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    addMigDefMain() {
      this.migDefMain = true
    },
    inputdbl(data) {},
    editFiled(data) {
      const query = data
      data.code = data.migId
      query.byid = true
      query.queryEdit = true
      query.PK_FIELD = 'migId'
      query.id = data.migId
      this.$router.push({
        name: 'MigDefEdit',
        query
      })
    },
    execMigTask(data) {
      var that = this
      var messageStr = '是否确定执行 ' + data.name
      this.$confirm(messageStr, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message('已开始执行')
          var params = { rtId: data.rtId } // 这里执行的时候传CODE
          migJobRelate.idMigrate(params).then(res => {
            that.crud.refresh()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消执行'
          })
        })
    },
    checkMainItem(data = []) {
      const that = this
      this.migDefMain = false
      data.map(i => {
        const item = {
          migId: i.id,
          jobId: that.form.jobId,
          name: i.name,
          code: i.code,
          querySql: i.querySql
        }
        migJobRelate.add(item).then(res => {
          this.queryChildList()
        })
      })
    },
    saveRowData(item) {
      migJobRelate.edit(item).then(function(res) {})
    }
  }
}
</script>

<style scoped>
.searchFiled {
  padding-right: 0;
}
</style>
